const jsonServer = require('json-server')
const bodyParser = require('body-parser');
const userRouter = require('./routes/user');
const biliRouter = require('./routes/bilibili');
const videoRouter = require('./routes/video');
let r = require(__dirname + '/db/db.js');
const cors = require('cors');
//创建 express 服务
const server = jsonServer.create()
//设置英雄 json
const router = jsonServer.router(r)
//设置静态资源服务
const middlewares = jsonServer.defaults({
    static: __dirname+'/public',
    noCors : false
})

function getClientIP(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress;
};

//记录请求的 ip 与请求的路径
let recordMiddleware = (req, res, next) => {
    let ip = getClientIP(req);
    require('fs').writeFileSync('./access.log', req.method + '---' + ip + '---' + req.url +'\r\n', {flag: 'a+'});
    next();
}

server.all('/server', (req, res) => {
    setTimeout(() => {
        res.setHeader('Access-Control-Allow-Origin', "*")
        res.send('OK');
    }, 3000)
})

server.use(middlewares);
server.use(recordMiddleware);
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json())
server.use(videoRouter,userRouter,biliRouter,router);

let port = 3002;
server.listen(port, () => {
    console.log(`JSON Server is running port ${port}`);
})